#include <cstring>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "Board.h"

using namespace std;

Board::Board() {
	srand(time(0));
	char possible_tile[3] = {NOTHING, SNAKE, LADDER};
	int x, y, to_put;

	num_snakes = num_ladders = 0;

	for(int i = 0; i < MAX_WIDTH; i++) {
		for(int j = 0; j < MAX_HEIGHT; j++) {
			to_put = NOTHING;
			// chance of 1/RAND_FACT a node is either 'S'nake or 'L'adder AND
			if((i != 0 || j != 0) && !(rand() % RAND_FACT)) {
				to_put = possible_tile[rand() % 3];
				
				// if LADDER and at the highest row or SNAKE at the bottom; put nothing
				if((to_put == LADDER && j == MAX_HEIGHT - 1) || (to_put == SNAKE && i == 0))
					to_put = NOTHING;
	
				if(to_put == SNAKE) {
					// add one as i or j maybe zero and we'll get division by 0
					x = rand() % (i+1);
					y = rand() % (j+1);
					
					// make sure snake actually penalizes player
					if(i == 0 && y == j) {
						y--;
					} else if(j == 0 && x == i) {
						x--;
					}

					jumpto[i][j].x = x;
					jumpto[i][j].y = y;
					num_snakes++;

				// make sure that ladder actually rewards player
				} else if(to_put == LADDER) {
					x = rand() % MAX_WIDTH;
					y = rand() % (MAX_HEIGHT - 1);

					// case lower height
					if(y < j) {
						y = j + 1;
					} else if(y == j) {
						// case equal height but lower width
						if(x <= i) {
							x = i + 1;
						}
					}

					jumpto[i][j].x = x;
					jumpto[i][j].y = y;
					num_ladders++;
				}
					
			}

			nodes[i][j] = to_put;
		}
	}
}

void Board::print_board(int mode) {
	string to_print;
	for(int j = MAX_HEIGHT - 1; j >= 0; j--) {	
		for(int i = 0; i < 10; i++) {
			switch(mode) {
				case PRINT_NT:
					to_print = nodes[i][j];
					break;
				case PRINT_BO:
					to_print = nodes[i][j];
					to_print.append(Util::print_point(i, j));
					break;
				case PRINT_PT: 
					to_print = Util::print_point(i, j);
					break;
			}

			cout << "|" << to_print;
		}
		cout << "|" << endl;
	}
}

void Board::print_jumpto() {
	for(int i = 0; i < MAX_WIDTH; i++) {
		for(int j = 0; j < MAX_HEIGHT; j++) {
			if(nodes[i][j] != NOTHING) {
				cout << nodes[i][j] << " - " << Util::print_point(i, j) << ": " << Util::print_point(jumpto[i][j]) << endl;
			}
		}
	}
}

void Board::print_info() {
	cout << "Number of ladders: " << num_ladders << endl;
	cout << "Number of snakes: " << num_snakes << endl;
}
